package com.tyros.common.config.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Mybatis Plus 相关配置
 *
 * @author zhangshuaiyin
 * @date 2022-1-15 21:49:54
 */
@Slf4j
@Configuration
@MapperScan("com.tyros.**.mapper")
public class MybatisPlusConfig {
    private final static String OPEN_ID = "openId";
    private final static String CREATE_TIME = "createTime";
    private final static String UPDATE_TIME = "updateTime";

    /**
     * 新版分页插件，注意选择数据库
     *
     * @return MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        log.info("Mybatis Plus 分页插件配置完成...");
        return interceptor;
    }

    /**
     * MyBatisPlus自定义字段自动填充处理类
     * 实体类中使用 @TableField 注解配置填充字段和填充策略
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            /**
             * 新增时填充
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                this.fillStrategy(metaObject, OPEN_ID, UUID.randomUUID().toString());
                this.fillStrategy(metaObject, CREATE_TIME, LocalDateTime.now());
                this.fillStrategy(metaObject, UPDATE_TIME, LocalDateTime.now());
            }

            /**
             * 更新时填充
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                this.fillStrategy(metaObject, UPDATE_TIME, LocalDateTime.now());
            }
        };
    }
}
